<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option :label="item.cate_name" :value="item.id" v-for="item in list" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="loadArtList">筛选</el-button>
            <el-button type="info" size="small" @click="resterArtList()">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="dialogVisible=true">发表文章</el-button>
      </div>
<el-dialog
  :fullscreen='true'
  title="提示"
  :visible.sync="dialogVisible"
  width="30%"
  :before-close="handleClose">
<!-- 发布文章的对话框 -->
        <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
          </el-form-item>
          <el-form-item label="文章分类" prop="cate_id">
            <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">
              <el-option :label="item.cate_name" :value="item.id" v-for="item in list" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!-- 文本域 -->
           <el-form-item label="文章文本" prop="content">
            <quill-editor v-model="pubForm.content" @blur="$refs.pubFormRef.validateField('content')" ></quill-editor>
           </el-form-item>
             <el-form-item label="文章封面" prop="cover_img" >
                    <!-- 用来显示封面的图片 -->
                    <img :src="preview" v-if="preview" alt="" class="cover-img" ref="imgRef" />
                    <img v-else src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
                    <br />
                    <!-- 文件选择框，默认被隐藏 -->
                    <input type="file" style="display: none;" accept="image/*" ref="iptFileRef" @change="loadImgFn" />
                    <!-- 选择封面的按钮 -->
                    <el-button type="text" @click="$refs.iptFileRef.click()">+ 选择封面</el-button>
           </el-form-item>
           <el-form-item>
              <el-button type="primary" size="mini" @click="upInfo('已发布')" >提交</el-button>
              <el-button type="info" size="mini" @click="upInfo('草稿')">信息按钮</el-button>
           </el-form-item>
        </el-form>
        </el-dialog>

         <el-table
      :data="artList"
      style="width: 100%">
      <el-table-column
        prop="title"
        label="文章标题">
          <template v-slot="{row}">
            <el-link type="primary" :underline="false" @click="showDialog(row.id)">{{row.title}}</el-link>
          </template>
      </el-table-column>
      <el-table-column
        prop="cate_name"
        label="文章分类">
      </el-table-column>
      <el-table-column
        prop="state"
        label="发布状态">
      </el-table-column>
       <el-table-column
        prop="pub_date"
        label="发布时间">
      <template v-slot="{row}">{{pubDate(row.pub_date)}}</template>
      </el-table-column>
       <el-table-column
        label="操作">
        <template v-slot="{row}">
        <el-button type="danger" size="mini" @click="delArtList(row.id)">删除</el-button>
        </template>
      </el-table-column>

        </el-table>
    </el-card>
     <!-- 分页区域 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="q.pagenum"
      :page-sizes="[2, 3, 5, 10]"
      :page-size="q.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- 点击标题 弹出 dialog -->
          <!-- <el-dialog
              title="提示"
              :visible.sync="showDialogVisible"
             :close-on-click-modal="false"
              width="80%"> -->
              <!-- 查看文章详情的对话框 -->
              <el-dialog title="文章预览" :visible.sync="showDialogVisible" width="80%">
                <h1 class="title">{{ artDetail.title }}</h1>

                <div class="info">
                  <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
                  <span>发布时间：{{ pubDate(artDetail.pub_date) }}</span>
                  <span>所属分类：{{ artDetail.cate_name }}</span>
                  <span>状态：{{ artDetail.state }}</span>
                </div>

                <!-- 分割线 -->
                <el-divider></el-divider>

                <!-- 文章的封面 -->
                <img :src="'http://www.liulongbin.top:3008' + artDetail.cover_img" alt="" />

                <!-- 文章的详情 -->
                <div v-html="artDetail.content" class="detail-box"></div>
              </el-dialog>
         <!-- </el-dialog> -->
  </div>
</template>

<script>
import dayjs from 'dayjs'
export default {
  name: 'ArtList',
  data () {
    return {
      showDialogVisible: false,
      dialogVisible: false,
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 3,
        cate_id: '',
        state: ''
      },
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: '',
        state: ''
      },
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [{ required: true, message: '请选择文章标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入本章内容', trigger: 'blur' }],
        cover_img: [{ required: true, message: '请选择文章封面', trigger: 'blur' }]
      },
      list: [],
      artList: [],
      preview: '',
      total: 0,
      artDetail: {}

    }
  },
  methods: {
    handleSizeChange (val) {
      this.q.pagesize = val
      this.q.pagenum = 1
      // console.log(`每页 ${val} 条`)
    },
    handleCurrentChange (val) {
      this.q.pagenum = val
      this.loadArtList()

      // console.log(`当前页: ${val}`)
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    async loadCateList () {
      const { data: res } = await this.$axios.get('/my/cate/list')
      // console.log(res)
      this.list = res.data
    },
    loadImgFn (e) {
      const file = e.target.files[0]
      if (file) {
        this.pubForm.cover_img = file
        this.preview = URL.createObjectURL(file)
      } else {
        this.preview = ''
        this.pubForm.cover_img = ''
      }
      this.$refs.pubFormRef.validateField('cover_img')
    },
    upInfo (state) {
      this.pubForm.state = state
      this.$refs.pubFormRef.validate(async valid => {
        if (!valid) return
        const fd = new FormData()
        // for (const k in this.pubForm) {
        //   fd.append(k, this.pubForm[k])
        // }
        Object.keys(this.pubForm).forEach(k => fd.append(k, this.pubForm[k]))
        const { data: res } = await this.$axios.post('/my/article/add', fd)
        // console.log(res)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.dialogVisible = false
        this.preview = ''
        this.$refs.pubFormRef.resetFields()
        this.loadArtList()
      })
    },
    async loadArtList () {
      const { data: res } = await this.$axios.get('/my/article/list', { params: this.q })
      console.log(res)
      this.artList = res.data
      this.total = res.total
    },
    pubDate (date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    delArtList (id) {
      console.log(id)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios({
          method: 'delete',
          url: '/my/article/info',
          params: {
            id
          }
        })
        // console.log(res)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.loadArtList()
      }).catch(() => {
      })
    },
    resterArtList () {
      this.q.cate_id = ''
      this.q.state = ''
      this.loadArtList()
    },
    async showDialog (id) {
      // console.log(id)
      this.showDialogVisible = true
      const { data: res } = await this.$axios.get('/my/article/info', { params: { id } })
      this.artDetail = res.data
    }
  },
  created () {
    this.loadCateList()
    this.loadArtList()
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
/deep/ .ql-editor{
  height: 300px;
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}
</style>
